package org.example.java.util.concurrency.thread.condition;

public class ThreadTest {
  static class Business {
    private boolean bool = true;

    public synchronized void main(int loop) throws InterruptedException {
      while (bool) {
        System.out.println(Thread.currentThread().getName() + " : loop await before");
        this.wait();
        System.out.println(Thread.currentThread().getName() + " : loop await end");
      }
      for (int i = 0; i < 10; i++) {
        System.out.println(Thread.currentThread().getName() + " : seq of " + i + ", loop of " + loop);
      }
      bool = true;
      this.notify();
    }

    public synchronized void sub(int loop) throws InterruptedException {
      while (!bool) {
        System.out.println(Thread.currentThread().getName() + " : loop await before");
        this.wait();
        System.out.println(Thread.currentThread().getName() + " : loop await end");
      }
      for (int i = 0; i < 10; i++) {
        System.out.println(Thread.currentThread().getName() + " : thread seq of " + i + ", loop of " + loop);
      }
      bool = false;
      this.notify();
    }
  }

  public static void main(String[] args) {
    final Business business = new Business();
    new Thread(new Runnable() {
      @Override
      public void run() {
        threadExecute(business, "sub");
      }
    }).start();
    threadExecute(business, "main");
  }

  public static void threadExecute(Business business, String threadType) {
    for (int i = 0; i < 10; i++) {
      try {
        if ("main".equals(threadType)) {
          business.main(i);
        } else {
          business.sub(i);
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}


